package com.example.webbrowser.Utils;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 *
 * 关于网络请求的工具类
 * 提供4个静态方法：判断是否有网络连接、若没有弹出网络设置、网络请求（OKHttp）和根据图片的url路径获得Bitmap对象
 */


public class HttpUtils {

    /**
     * 判断网络情况
     *
     * @param context 上下文
     * @return false 表示没有网络 true 表示有网络
     */
    public static boolean isNetworkAvalible(Context context) {
        // 获得网络状态管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 建立网络数组
            NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();

            if (net_info != null) {
                for (int i = 0; i < net_info.length; i++) {
                    // 判断获得的网络状态是否是处于连接状态
                    if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }



    public static String requestHttp(String url) {
        String responseData = null;
        try {
            OkHttpClient client = new OkHttpClient(); //创建OkHttpClient实例
            Request request = new Request.Builder()   //创建一个Request对象
                    .url(url)
                    .build();

            //调用OkHttpClient的newCall()方法来创建一个Call对象，并调用它的execute()方法发送请求并获取数据
            Response response = client.newCall(request).execute();
            responseData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseData;
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     */
    public static Bitmap decodeUriAsBitmapFromNet(String imgUrl) {
        if(TextUtils.isEmpty(imgUrl)){
            return null;
        }
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(imgUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            assert fileUrl != null;
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);          //设置成输入
            conn.connect();
            InputStream is = conn.getInputStream();   //从网络获取到的输入流
            bitmap = BitmapFactory.decodeStream(is);  //将输入流解码得到bitmap对象
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
